<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>上传图片</title>
</head>

<body>


    <img class="photo photo-img" src="">
    <form id="img_form" action="http://localhost:3000/upload/img" method="POST" enctype="multipart/form-data">
        <!-- <input name="img" type="file" id="img-input" onchange="changeImg()" /> -->

        <input type="file" name="img">
        <input type="submit" value="点击上传">

    </form>

    <script src="https://cdn.bootcss.com/jquery/3.3.0/jquery.min.js"></script>
    <script>
        var domain = 'http://localhost:3000'

        function changeImg() {
            // 图片更改后异步提交表单上传服务器，返回url
            var form = $("#img_form");
            var options = {
                url: domain + '/upload/img', //上传文件的路径
                type: 'post',
                success: function (data) {
                    data = JSON.parse(data);
                    if (data.code == 0) {
                        imgUrl = data.data.url;
                    } else {
                        alert('上传图片出错！');
                    }
                }
            };
            form.ajaxSubmit(options);

            // 在前端显示上传的图片
            var file = $('.photo').find('input')[0].files[0];
            var reader = new FileReader();
            reader.onload = function (e) {
                var imgFile = e.target.result;
                $('.photo-img').attr('src', imgFile);
                $('.photo-img').attr('style', 'display:block');
            }
            reader.readAsDataURL(file);
        }
    </script>

</body>

</html>